package m202405.d14;

import java.util.Stack;

/**
 * @@author: 爱做梦的锤子
 * @date: 2024/5/14 17:52
 */
public class Q394 {

    public static void main(String[] args) {
        Q394 q394 = new Q394();
        q394.decodeString("3[a]2[bc]");
    }

    public String decodeString(String s) {
        Stack<String> stack = new Stack<>();
        for (int i = 0; i < s.length(); i++) {
            char c = s.charAt(i);
            if (c == ']') {
                StringBuilder str = new StringBuilder();
                while (!"[".equals(stack.peek())) {
                    str.insert(0, stack.pop());
                }
                stack.pop();
                String peek = stack.peek();
                StringBuilder n = new StringBuilder();
                while (!stack.isEmpty() && peek.charAt(0) <= '9' && peek.charAt(0) >= '0') {
                    n.insert(0, stack.pop());
                    peek = stack.isEmpty() ? null : stack.peek();
                }
                stack.push(mark(Integer.parseInt(n.toString()), str.toString()));
                continue;
            }
            stack.push(String.valueOf(c));
        }
        StringBuilder res = new StringBuilder();
        while (!stack.isEmpty()) {
            res.insert(0, stack.pop());
        }
        return res.toString();
    }

    private String mark(int n, String s) {
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < n; i++) {
            sb.append(s);
        }
        return sb.toString();
    }
}
